package com.elinkway.infinitemovies.selfdata.dao;

import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.MyRecordBean;
import com.google.gson.Gson;

import java.util.List;

import io.realm.OrderedRealmCollectionSnapshot;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Author: liuxiaojiang(xiao)
 * Date: 2017-07-07
 * Time: 10:24
 * Description: FIXME
 */
public class MyDataDao extends BaseRealmDao<MyRecordBean> {

    public void add(MyDataRecord myDataRecord) {
        if (myDataRecord != null) {
            Gson gson = new Gson();
            MyRecordBean bean = new MyRecordBean();
            bean.setRecordVlaue(gson.toJson(myDataRecord));
            myBaseDaoRealm.beginTransaction();
            MyRecordBean data = myBaseDaoRealm.copyToRealm(bean); // Create a new object
            myBaseDaoRealm.commitTransaction();
        }
    }

    public void delete() {
        myBaseDaoRealm.delete(MyRecordBean.class);
    }

    public void delete(final RealmResults<MyRecordBean> result) {
        myBaseDaoRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                result.deleteAllFromRealm();
            }
        });
    }

    public void deleteSnapshot(final OrderedRealmCollectionSnapshot<MyRecordBean> mResultsSnapshot) {
        myBaseDaoRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                mResultsSnapshot.deleteAllFromRealm();
            }
        });
    }

    public RealmResults<MyRecordBean> findAll(){
        return myBaseDaoRealm.where(MyRecordBean.class).findAll();
    }

    public List<MyRecordBean> realmResultsToList(RealmResults<MyRecordBean> records){
        return myBaseDaoRealm.copyFromRealm(records);
    }

    public List<MyRecordBean> queryAll() {
        RealmResults<MyRecordBean> records = myBaseDaoRealm.where(MyRecordBean.class).findAll();
        /**
         * 对查询结果，按Id进行排序，只能对查询结果进行排序
         */
        //增序排列
//        records=records.sort("id");
        //降序排列
//        records=records.sort("id", Sort.DESCENDING);
        return myBaseDaoRealm.copyFromRealm(records);
    }


}
